//导入文件
const gulp = require('gulp');
const cssmin = require('gulp-cssmin');
const autoprefixer = require('gulp-autoprefixer');
const uglify = require('gulp-uglify');
const babel = require('gulp-babel');
const htmlmin = require('gulp-htmlmin');
const del = require('del');
const webserver = require('gulp-webserver');

//压缩html
const htmlHandler = ()=>{
    return gulp.src('./src/pages/**')
    .pipe(htmlmin({
        collapseWhitespace:true,
        minifyCSS:true,
        minifyJS:true,
        removeAttributeQuotes:true,
        removeComments:true
    }))
    .pipe(gulp.dest('./dist/pages/'))
}
//压缩js
const jsHandler = ()=>{
    return gulp.src('./src/js/**')
    .pipe(babel({
        presets:['@babel/env']
    }))
    .pipe(uglify())
    .pipe(gulp.dest('./dist/js/'))
}
//压缩css
const cssHandler = ()=>{
    return gulp.src('./src/css/**')
    .pipe(autoprefixer())
    .pipe(cssmin())
    .pipe(gulp.dest('./dist/css/'))
}
//压缩主页
const indexHandler = ()=>{
    return gulp.src('./src/index.html')
    .pipe(htmlmin({
        collapseWhitespace:true,
        minifyCSS:true,
        minifyJS:true,
        removeAttributeQuotes:true,
        removeComments:true
    }))
    .pipe(gulp.dest('./dist/'))
}
//压缩php
const phpHander = ()=>{
    return gulp.src('./src/php/**')
    .pipe(gulp.dest('./dist/php/'))
}
//压缩images
const imgHandler = ()=>{
    return gulp.src('./src/images/**')
    .pipe(gulp.dest('./dist/images/'))
}
//压缩font
const fontHandler = ()=>{
    return gulp.src('./src/font/**')
    .pipe(gulp.dest('./dist/font/'))
}
//压缩fonts
const fontsHandler = ()=>{
    return gulp.src('./src/font_shanchu/**')
    .pipe(gulp.dest('./dist/font_shanchu/'))
}
//开启web服务器
const serverHandler = ()=>{
    return gulp.src('./dist')
    .pipe(webserver({
        port:8080,
        open:'./index.html',
        livereload:true,
        proxies:[{
            source:'/cyr',
            target:"http://127.0.0.1/test.php"
        }]
    }))
}
//删除文件
const delHandler = ()=>{
    return del("./dist")
}
//监控文件
const watchHandler = ()=>{
    gulp.watch('./src/css/**',cssHandler);
    gulp.watch('./src/js/**',jsHandler);
    gulp.watch('./src/php/**',phpHander);
    gulp.watch('./src/pages/**',htmlHandler);
    gulp.watch('./src/index.html',indexHandler);
    gulp.watch('./src/images/**',imgHandler);
    gulp.watch('./src/font/**',fontHandler);
    gulp.watch('./src/font_shanchu/**',fontsHandler);
}
module.exports.default = gulp.series(
    delHandler,
    gulp.parallel(phpHander,imgHandler,cssHandler,jsHandler,fontHandler,htmlHandler,fontsHandler,indexHandler),
    serverHandler,
    watchHandler
)